/**
 * Description:
 *
 * @author      Eden
 * @datetime    2016/12/10 23:26
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */
(function () {

    sm.controller('admin-bbs-publish-controller', ['$scope', '$http', 'Modal', function ($scope, $http, Modal) {

        function upload() {
            // 初始化Web Uploader
            var uploader = WebUploader.create({
                auto: true,
                server: '/bbs/publish/uploadAttachment',
                pick: '#thumbBtn',
                swf: '/assets/library/webuploader/Uploader.swf',
                duplicate: true,
                accept: {
                    title: 'Images',
                    extensions: 'gif,jpg,jpeg,png'
                }
            });

            // 成功
            uploader.on('uploadSuccess', function(file, res) {
                if (res.state) {
                    var data = res.data;
                    $scope.attachment.push({
                        thumb: data.thumb || '',
                        source: data.source || '',
                        save: data.key
                    });
                } else {
                    var error = res.error ? res.error : '上传失败';
                    Modal.error(error);
                }
            });

            uploader.on('uploadComplete', function( file ) {
                $scope.$apply();
                delete uploader;
                upload();
            });
        }

        $scope.attachment = [];
        $scope.content = '';
        $scope.likes = 0;

        // ===========
        upload();

        $scope.submit = function () {

            var data = {};
            if (!$scope.content || WordCount($scope.content) <= 10) {
                Modal.error('主题内容不能小于10个汉字');
                return false;
            } else {
                data.content = $scope.content;
            }

            data.likes = 0;
            if ($scope.likes && $scope.likes != 0) {
                data.likes = parseInt($scope.likes);
            }

            data.attachment = [];
            if ($scope.attachment.length > 0) {
                angular.forEach($scope.attachment, function (val) {
                    data.attachment.push(val['save']);
                });
            }

            Modal.alert({
                title: '您确定发布该主题吗?',
                content: '请确保主题内容没有不良引导，挑衅、恶意言论',
                buttons: [{
                    name: '取消',
                    type: 'cancel'
                }, {
                    name: '立即发布',
                    event: function () {
                        doSubmit(data);
                    }
                }]
            });

        };

        /**
         * 执行提交
         * @param data
         */
        function doSubmit(data) {
            $http.post('/bbs/publish/submit', data).success(function (res) {
                console.log(res);
            });
        }


    }]);

})();